'use client';

import { useState, useEffect, useCallback, useRef, ChangeEvent, TextareaHTMLAttributes } from 'react';
import { useSocket } from './socket-io-provider';
import { debounce } from 'lodash';

interface CollaborativeEditorProps extends Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, 'onChange'> {
  projectId: string;
  value: string;
  onChange: (value: string) => void;
}

// 定义更新事件类型
interface ContentUpdateEvent {
  projectId: string;
  content: string;
  userId?: string;
  timestamp: number;
}

export default function CollaborativeEditor({
  projectId,
  value,
  onChange,
  ...props
}: CollaborativeEditorProps) {
  const { socket, isConnected, users } = useSocket();
  const [localContent, setLocalContent] = useState(value);
  const [lastRemoteUpdate, setLastRemoteUpdate] = useState<number>(0);
  const [cursors, setCursors] = useState<Record<string, any>>({});
  const editorRef = useRef<HTMLTextAreaElement>(null);
  
  // 发送光标位置
  const emitCursorPosition = useCallback(
    debounce((position: number) => {
      if (socket && isConnected) {
        console.log('[CollaborativeEditor] 发送光标位置:', position);
        socket.emit('cursor-update', {
          projectId,
          position,
          timestamp: Date.now()
        });
      }
    }, 100),
    [socket, isConnected, projectId]
  );
  
  // 处理选择/光标变化
  const handleSelectionChange = () => {
    if (!editorRef.current) return;
    const position = editorRef.current.selectionStart;
    emitCursorPosition(position);
  };
  
  // 当本地内容变化时，发送更新事件
  const emitContentUpdate = useCallback(
    debounce((content: string) => {
      if (socket && isConnected) {
        console.log('[CollaborativeEditor] 发送内容更新，长度:', content.length);
        const updateEvent: ContentUpdateEvent = {
          projectId,
          content,
          timestamp: Date.now()
        };
        socket.emit('content-update', updateEvent);
        
        // 为调试目的记录发送事件
        console.log('[CollaborativeEditor] 内容更新事件已发送', {
          projectId,
          contentLength: content.length,
          timestamp: Date.now()
        });
      }
    }, 200), // 减少延迟到200ms，提高响应速度
    [socket, isConnected, projectId]
  );

  // 处理文本变化
  const handleTextChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
    const newContent = e.target.value;
    setLocalContent(newContent);
    onChange(newContent);
    
    // 发送更新到其他客户端
    emitContentUpdate(newContent);
  };

  // 监听其他用户的内容更新
  useEffect(() => {
    if (!socket || !isConnected) return;

    const handleContentUpdate = (data: ContentUpdateEvent) => {
      try {
      // 确保更新来自同一个项目
      if (data.projectId !== projectId) return;
      
      // 避免处理过期的更新
      if (data.timestamp && data.timestamp <= lastRemoteUpdate) {
        console.log('[CollaborativeEditor] 忽略较旧的更新', {
          currentTimestamp: lastRemoteUpdate,
          incomingTimestamp: data.timestamp
        });
        return;
      }
      
      console.log('[CollaborativeEditor] 收到内容更新', data);
      
      // 更新最后接收时间戳
      if (data.timestamp) {
        setLastRemoteUpdate(data.timestamp);
      }
      
      // 更新本地内容
      setLocalContent(data.content);
      onChange(data.content);
      
      // 显示通知
      if ('Notification' in window && Notification.permission === 'granted') {
        new Notification('内容已更新', {
          body: '其他用户修改了文档内容',
          icon: '/favicon.ico'
        });
      }
      } catch (error) {
        console.error('[CollaborativeEditor] 处理内容更新出错:', error);
      }
    };

    console.log('[CollaborativeEditor] 添加content-update事件监听器');
    socket.on('content-update', handleContentUpdate);
      
      // 监听用户加入
      socket.on('user-joined', (userData) => {
        console.log('[CollaborativeEditor] 新用户加入:', userData);
      });
      
      // 添加测试事件处理器
      socket.on('connection-test', (data) => {
        console.log('[CollaborativeEditor] 收到连接测试:', data);
      });

    return () => {
      console.log('[CollaborativeEditor] 移除事件监听器');
      socket.off('content-update', handleContentUpdate);
      socket.off('user-joined');
      socket.off('connection-test');
    };
  }, [socket, isConnected, projectId, onChange, lastRemoteUpdate]);

  // 同步props的value到本地状态
  useEffect(() => {
    if (value !== localContent) {
      setLocalContent(value);
    }
  }, [value]);
  
  // 请求通知权限
  useEffect(() => {
    if ('Notification' in window && Notification.permission === 'default') {
      // 等待用户与页面交互后再请求权限
      const requestPermission = () => {
        Notification.requestPermission().then(permission => {
          console.log('[CollaborativeEditor] 通知权限:', permission);
        });
        // 移除事件监听器
        document.removeEventListener('click', requestPermission);
      };
      
      document.addEventListener('click', requestPermission);
      return () => {
        document.removeEventListener('click', requestPermission);
      };
    }
  }, []);

  // 添加滚动事件处理
  useEffect(() => {
    if (editorRef.current) {
      const handleScroll = () => {
        console.log('[CollaborativeEditor] 滚动位置:', editorRef.current?.scrollTop);
      };
      
      editorRef.current.addEventListener('scroll', handleScroll);
      
      return () => {
        editorRef.current?.removeEventListener('scroll', handleScroll);
      };
    }
  }, [editorRef.current]);

  return (
    <div className="relative w-full">
      {!isConnected ? (
        <div className="absolute top-2 right-2 bg-yellow-100 text-yellow-800 text-xs px-2 py-1 rounded-full z-10">
          离线模式
        </div>
      ) : (
        <div className="absolute top-2 right-2 bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full z-10">
          协作模式 ({users?.length || 1}人)
        </div>
      )}
      <textarea
        ref={editorRef}
        {...props}
        className={`w-full min-h-[500px] p-4 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent ${props.className || ''}`}
        value={localContent}
        onChange={handleTextChange}
        onKeyUp={handleSelectionChange}
        onClick={handleSelectionChange}
      />
    </div>
  );
}
 